package com.fable.common.configura.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Component
public class AuthenticationFilter extends AccessControlFilter {

    private Logger _log = LoggerFactory.getLogger(getClass());

    @Autowired
    ShiroConfigProperties configProperties;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        return subject.isAuthenticated();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = null;
        if ((request instanceof HttpServletRequest)) {
            httpRequest = (HttpServletRequest) request;
        } else {
            _log.error("request is not HttpServletRequest");
        }

        // /api和/sys/api接口视为ajax请求
        if (httpRequest.getServletPath().startsWith("/api")) {
            httpRequest.getRequestDispatcher(configProperties.getUnAuthenticatedApi()).forward(request, response);
        } else {
            httpRequest.getRequestDispatcher(configProperties.getUnAuthenticatedPage()).forward(request, response);
        }

        return false;
    }
}
